package hr.koshnica.android.ui.search;

import hr.koshnica.android.R;
import hr.koshnica.android.database.KoshnicaContract;
import hr.koshnica.android.database.KoshnicaContract.Search;
import hr.koshnica.android.ui.MainActivityV2;
import hr.koshnica.android.ui.SearchActivity;

import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.astuetz.viewpagertabs.ViewPagerTabProvider;
import com.astuetz.viewpagertabs.ViewPagerTabs;


public class SlidingTabsPagerSearch extends SherlockFragmentActivity{

	private ViewPager mViewPager;
	private ViewPagerTabs mTabs;
	private TestPagerAdapter mAdapter;
	private LinearLayout mSearchBar;
	private EditText mSearchView;
	private ListView searchLv;
	private Cursor searchCrs;
	private Activity activity = this;

	private static final int MENU_FILTER = 100;
	private static final int MENU_SHARE = 200;
	private static final int MENU_SEARCH = 300;
    
    private final boolean[] mSelectionCondictionsAB = {true, true, true};
    private final boolean[] mSelectionCondictionsLoc = {true, true, true};

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	
		menu.add(0, MENU_FILTER, 0, getString(R.string.sliding_tabs_pager_search_action_bar_menu_filter))
			
			.setIcon(R.drawable.ic_menu_moreoverflow)
		    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		menu.add(0, MENU_SHARE, 0, getString(R.string.sliding_tabs_pager_search_action_bar_menu_share))
		    .setIcon(R.drawable.ic_title_share_default)
		    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		
		menu.add(0, MENU_SEARCH, 0, getString(R.string.sliding_tabs_pager_search_action_bar_menu_search))
        .setIcon(R.drawable.ic_search)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		
		
		return super.onCreateOptionsMenu(menu);
	}
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case android.R.id.home:
	            // app icon in action bar clicked; go home
	            Intent intent = new Intent(this, MainActivityV2.class);
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            
	            SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
		   	    		R.layout.list_row_search_2, null, null, null);			        
		   	 	searchLv.setAdapter(resultsAdapter);
		   	    mSearchView.setText("");
				mSearchBar.setVisibility(View.GONE);
				mTabs.setVisibility(View.VISIBLE);
				
	            startActivity(intent);
	            return true;

            case MENU_FILTER: 
            	final CharSequence[] items = {"Muzika", "Udaljenost", "Uzarenost"};
    			
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			builder.setTitle("Sortiraj po: ");
    			builder.setMultiChoiceItems(items, mSelectionCondictionsAB, new DialogInterface.OnMultiChoiceClickListener() {
    			    @Override
					public void onClick(DialogInterface dialog, int whichItem, boolean isChecked) {
    			    	mSelectionCondictionsAB[whichItem] = isChecked;
    			    	
    			        
    			    }
    			}).setPositiveButton("Ok",
    			        new DialogInterface.OnClickListener() {

    	            @Override
					public void onClick(DialogInterface dialog,
    	                    int whichButton) {
    	                    }
    	                }).create();
    			builder.show();
                
                return true;
            
            case MENU_SHARE: 
            	Toast.makeText(SlidingTabsPagerSearch.this, "Example action",
    					Toast.LENGTH_SHORT).show();
                
                return true;
                
            case MENU_SEARCH:
            	
            	mSearchBar.setVisibility(View.VISIBLE);
            	mTabs.setVisibility(View.GONE);           
                
                return true;
            
            default:
                return super.onOptionsItemSelected(item);
        }

    }
    
    public void itemImgViewClicked(View view){
    	Toast.makeText(SlidingTabsPagerSearch.this, "Pressed item Button",
				Toast.LENGTH_SHORT).show();
    	
    	final CharSequence[] items = {"Svida mi se", "Favoriti", "Ne prikazuj vise"};
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setMultiChoiceItems(items, mSelectionCondictionsLoc, new DialogInterface.OnMultiChoiceClickListener() {
		    @Override
			public void onClick(DialogInterface dialog, int whichItem, boolean isChecked) {
		    	mSelectionCondictionsLoc[whichItem] = isChecked;
		    	
		        
		    }
		}).setPositiveButton("Ok",
		        new DialogInterface.OnClickListener() {

            @Override
			public void onClick(DialogInterface dialog,
                    int whichButton) {
                    }
                }).setNegativeButton("Odustani", new DialogInterface.OnClickListener() {
                    @Override
					public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                   }
               }).create();
		builder.show();
       
	}
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sliding_tabs_pager_search);
   
        getSupportActionBar().setTitle(getResources().getString(R.string.btn_search_main));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        
        ArrayList<String> fragments = new ArrayList<String>();
        fragments.add(LocationsFragment.class.getName());
        fragments.add(LocationsFragment.class.getName());
        fragments.add(LocationsFragment.class.getName());
      
        mSearchBar = (LinearLayout)findViewById(R.id.searchbarSlidingTabsPagerTest);
            
        searchLv = (ListView) findViewById(R.id.ListView01);
		mSearchView = (EditText) mSearchBar.findViewById(R.id.searchboxSlidingTabsPagerTest);
		
		searchLv.setOnItemClickListener(new OnItemClickListener()
		{
		    @Override
		    public void onItemClick(AdapterView<?> a, View view, int position, long id)
		    {
		    	TextView tv = (TextView)view.findViewById(R.id.valueRowSearch2);    	
		    	String path = (String)tv.getText();
		    	StringTokenizer tokens = new StringTokenizer(path, "/");
		    	String first = tokens.nextToken();
		    	String second = tokens.nextToken();	    	
		    	onShowItemDetails(second, first);
		    }
		});
		
		searchLv.setEmptyView(findViewById(R.id.pager));
		mSearchView.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable s){
				// Abstract Method of TextWatcher Interface.		
			}	
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {	
				// Abstract Method of TextWatcher Interface.		
			}		
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)	{	
				String str = mSearchView.getText().toString();
				System.out.println(str);			
				
				searchCrs = getContentResolver().query(Search.CONTENT_URI,
		                null, null, new String[] {
	                    str
	                }, null);
				
				 startManagingCursor(searchCrs);
			        String[] from = new String[] {            
			   			 	Search.TITLE,	            
			   				Search.OVERVIEW,
			   				Search.EXTRA_DATA			   				
			        };
			         
			        int[] to = new int[] {
			                R.id.textListRowSearch21, 
			                R.id.textListRowSearch22,
			                R.id.valueRowSearch2			                
			        };
			        SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),
			                R.layout.list_row_search_2, searchCrs, from, to);
			        
			        searchLv.setAdapter(resultsAdapter);

			        stopManagingCursor(searchCrs);
			}
		});
        
		ImageButton imgBtn = (ImageButton) mSearchBar.findViewById(R.id.searchbuttonSlidingTabsPagerTest);
		imgBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {				 
            	
				Intent i = new Intent(Intent.ACTION_SEARCH);
				String term = mSearchView.getText().toString();
				i.putExtra(SearchManager.QUERY, term);
				i.setClass(activity, SearchActivity.class);
				
				SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
            			R.layout.list_row_search_2, null, null, null);			        
			        
            	searchLv.setAdapter(resultsAdapter);			        
            	mSearchView.setText("");
				mSearchBar.setVisibility(View.GONE);
            	mTabs.setVisibility(View.VISIBLE);
            	
				startActivity(i);
			}
		});
          
        mAdapter = new TestPagerAdapter(this, getSupportFragmentManager(), fragments);
		
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mAdapter);
		
		mTabs = (ViewPagerTabs) findViewById(R.id.tabs);
		mTabs.setViewPager(mViewPager);
		
		mTabs.setTextColor(0xFF999999);
		mTabs.setTextColorCenter(0xFF999999);		
		mTabs.setLineHeight(0);
		
		Button btn = (Button) this
				.findViewById(R.id.searchbackSlidingTabsPagerTest);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
            			R.layout.list_row_search_2, null, null, null);			        
			        
            	searchLv.setAdapter(resultsAdapter);			        
            	mSearchView.setText("");
				mSearchBar.setVisibility(View.GONE);
            	mTabs.setVisibility(View.VISIBLE);    
			}
		});
        /*
        //Set the pager with an adapter      
        ViewPager pager = (ViewPager)findViewById(R.id.pager);
        pager.setAdapter(new TestPagerAdapter(this, getSupportFragmentManager(), fragments));

        //Bind the title indicator to the adapter
        TitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.titles);
        titleIndicator.setViewPager(pager);
        titleIndicator.setFooterIndicatorStyle(IndicatorStyle.Triangle);
          */                
        if (savedInstanceState != null) {
        	mTabs.setViewPager(mViewPager, savedInstanceState.getInt("index"));       	
        }
        
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("index", 2);
    }
    
    private void onShowItemDetails(String id, String path) {
    	
		if (path.equals(KoshnicaContract.PATH_LOCATIONS)) {    		 	    		 
			Intent i = new Intent(this, LocDescActivity.class);    	     
			i.putExtra("index", Integer.parseInt(id));
			
			SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
	   	    		R.layout.list_row_search_2, null, null, null);			        
	   	 	searchLv.setAdapter(resultsAdapter);
			mSearchView.setText("");
			mSearchBar.setVisibility(View.GONE);
        	mTabs.setVisibility(View.VISIBLE);
        	
			startActivity(i); 	         	
	    } else if (path.equals(KoshnicaContract.PATH_EVENTS)) { 
	    	Intent i = new Intent(this, LocDescActivity.class);
	   	    i.putExtra("index", Integer.parseInt(id));
	   	    
	   	    SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
	   	    		R.layout.list_row_search_2, null, null, null);			        
	   	 	searchLv.setAdapter(resultsAdapter);
	   	    mSearchView.setText("");
			mSearchBar.setVisibility(View.GONE);
			mTabs.setVisibility(View.VISIBLE);
	   	    
			startActivity(i);
	    	
	    }          
	    
	}

    public static class TestPagerAdapter extends FragmentStatePagerAdapter implements
    ViewPagerTabProvider {

    	private String[] mTitles;
		private ArrayList<String> mFragments;
		private Context mContext;
				
		public TestPagerAdapter(Context context, FragmentManager fm, 
				ArrayList<String> fragments) {
		    super(fm);
		    mFragments = fragments;
		    mContext = context;
		    Resources res = mContext.getResources();
		    mTitles = res.getStringArray(R.array.sliding_tabs_pager_search_tabs);
		}
	
		@Override
		public Object instantiateItem(View container, int position) {
		    return Fragment.instantiate(mContext, mFragments.get(position), null);
		}
		
		@Override
		public Fragment getItem(int position) {
		    return Fragment.instantiate(mContext, mFragments.get(position), null);
		}
		
		@Override
		public int getCount() {
		    return mFragments.size();
		}
		
		@Override
		public String getTitle(int position) {
		    
		    return mTitles[position];
		}

    } 

	
}